package com.wsc.services.util;


import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.*;
import java.util.Properties;

/**
 * Velocity工具包
 */
public class VelocityUtil {

    static Properties properties;
    static {
        properties = new Properties();
        properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,"");
        properties.setProperty(Velocity.ENCODING_DEFAULT,"UTF-8");
        properties.setProperty(Velocity.INPUT_ENCODING,"UTF-8");
    }

    /**
     * 获取字符
     * @return 模板生成的字符串
     */
    public String getTemplateString(String path,String key,Object model) throws Exception {
        StringWriter sw = new StringWriter();
        String s = null;
        try {
            Velocity.init(properties);
            VelocityContext vc = new VelocityContext();
            vc.put(key,model);
            Template tmp = Velocity.getTemplate(path);
            tmp.merge(vc,sw);
            s = sw.toString();
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }finally {
            sw.close();
        }
        return s;
    }

    /**
     * 生成模板
     *
     */
    public void writeTemplate(String path,String toPath, String key,Object model) throws Exception {
        BufferedWriter bw = null;
        try {
            Velocity.init(properties);
            VelocityContext vc = new VelocityContext();
            vc.put(key,model);
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toPath),"UTF-8"));
            Template tmp = Velocity.getTemplate(path);
            tmp.merge(vc,bw);
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }finally {
            if(bw !=null) bw.close();
        }
    }

}
